package com.luty.rpc.register;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by liuyunxin on 2017/7/1.
 */
public class ServiceRegister {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegister.class);
    private final ZkClient zkClient;

    public ServiceRegister(String address){
        System.out.println(address);
        zkClient = new ZkClient(address,Constant.ZK_SESSION_TIME, Constant.ZK_CONNETCTION_TIMEOUT);
        LOGGER.debug("zookeeper connect");
    }

    public void register(String serviceName, String serviceAddress){
        //创建 Register 节点（永久）
        String registerPath = Constant.ZK_REGISTER_NAME;
        if(zkClient.exists(registerPath)) {
            zkClient.deleteRecursive(registerPath);
        }
        zkClient.createPersistent(registerPath);
        LOGGER.debug("create server node : {}",registerPath);
        //创建 service 节点（永久）
        String servicePath = registerPath + "/" + serviceName;

        zkClient.createPersistent(servicePath);
        LOGGER.debug("create service node: {}", servicePath);
        //创建 address 节点（临时）
        String addressPath = servicePath + "/address-";

        zkClient.createPersistent(addressPath);
        String addressNode = zkClient.createEphemeralSequential(addressPath, serviceAddress);
        LOGGER.debug("create address node: {}", addressNode);



    }

}
